/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.prisetree.isv.common.util;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.isv.access.biz.prisetree.dao.SysDictDao;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.prisetree.isv.domain.ExpirableCache;
import com.prisetree.isv.domain.SysDict;


/**
 * 字典工具类
 * @author ThinkGem
 * @version 2013-5-29
 */
public class DictUtils {
	
	private static SysDictDao dictDao = SpringContextHolder.getBean(SysDictDao.class);

	public static final String CACHE_DICT_MAP = "dictMap";
	
	public static HashMap<String,ExpirableCache<SysDict>> DICT_MAP= Maps.newHashMap();
	
	public static String getDictLabel(String value, String type, String defaultValue){
		if(StringUtils.isNotBlank(type) && StringUtils.isNotBlank(value)){
			for (SysDict dict : getDictList(type)){
				if (type.equals(dict.getType()) && value.equals(dict.getValue())){
					return dict.getLabel();
				}
			}
		}
		
		return defaultValue;
	}
	
	public static String getDictLabels(String values, String type, String defaultValue){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(values)){
			List<String> valueList = Lists.newArrayList();
			for (String value : StringUtils.split(values, ",")){
				valueList.add(getDictLabel(value, type, defaultValue));
			}
			return StringUtils.join(valueList, ",");
		}
		return defaultValue;
	}

	public static String getDictValue(String label, String type, String defaultLabel){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(label)){
			for (SysDict dict : getDictList(type)){
				if (type.equals(dict.getType()) && label.equals(dict.getLabel())){
					return dict.getValue();
				}
			}
		}
		return defaultLabel;
	}
	
	
	public static List<SysDict> getDictList(String type){
		ExpirableCache<SysDict> list=DICT_MAP.get(type);
		if(list==null || list.isExpired()){
		    SysDict dict= new SysDict();
			dict.setType(type);
			List<SysDict> dicts=dictDao.find(dict);
			if(dicts!=null){
				// 设置两小时有效期
				Calendar date = Calendar.getInstance();
				date.add(Calendar.HOUR_OF_DAY, 2);
				DICT_MAP.put(type, new ExpirableCache<SysDict>(dicts, date.getTime()));
				return dicts;
			}
		}
		return list.getList();
	}
	
	public static String getJsonDict(String type)
	{
		JSONObject obj = new JSONObject();
		List<SysDict> list = getDictList(type);
		if(list != null)
		{
			for(SysDict d : list)
			{
				obj.put(d.getValue(), d.getLabel());
			}
		}
		return obj.toJSONString();
	}
	
}
